<?php
namespace app\manage\controller;

use app\manage\controller\BaseController;
use think\facade\Db;
use think\facade\View;
use app\manage\model\System as Systemmodel;
use lizhili\Time;

class System extends BaseController
{
    public function index()
    {
        $system = new Systemmodel();
        $key=input('key','');
        $data=$system->whereor('cnname|enname|value|desc', 'like', '%'.$key.'%')->order('sort asc')->select();
        View::assign('data', $data);
        $count1=Db::name('system')->count();
        View::assign('count1', $count1);
        return View::fetch();
    }
    public function ajax()
    {
        $data=input('post.');
        $system=new Systemmodel();
        if ($data['type']=='system_del') {
            if ($system->where('id',$data['id'])->delete()) {
                return json(['code' => 1, 'message' => '操作成功']);
            } else {
                return json(['code' => 0, 'message' => '操作失败']);
            }
        }
        if ($data['type']=='system_sort') {
            $arrlength=count($data['id']);
            $ar=[];
            for ($x=0;$x<$arrlength;$x++) {
                $ar[$x]=['id'=>$data['id'][$x], 'sort'=>$data['sort'][$x]];
            }
            $info=$system->saveAll($ar);
            if ($info) {
                return json(['code' => 1, 'message' => '操作成功']);
            } else {
                return json(['code' => 0, 'message' => '操作失败']);
            }
        }
        return 0;
    }
    public function add()
    {
        if (request()->isPost()) {
            $data=input('post.');
            $validate = new \app\manage\validate\System;
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }
            $data['kxvalue']=str_replace("，", ",", $data['kxvalue']);
            $data['value']=explode(",", $data['kxvalue'])[0];
            $user = new Systemmodel($data);
            if ($user->save()) {
                $this->success('添加成功', url('system/index', ['st'=>1]));
            } else {
                $this->error('添加失败了');
            }
        }
        return View::fetch();
    }
    public function edit()
    {
        if (request()->isPost()) {
            $data=input('post.');
            $validate = new \app\manage\validate\System;
            if ($data['st'] != 1) {
                if (!$validate->scene('edit')->check($data)) {
                    $this->error($validate->getError());
                }
            }
            $data['kxvalue']=str_replace("，", ",", $data['kxvalue']);
            if (Systemmodel::update($data, ['id' => input('id')])) {
                $this->success('添加成功', url('system/index', ['st'=>1]));
            } else {
                $this->error('修改失败了');
            }
        }
        $cid=input('id');
        $data=Db::name('system')->where('id', $cid)->find();
        View::assign('data', $data);
        return View::fetch();
    }
    
    public function show()
    {
        $system = new Systemmodel();
        if (request()->isPost()) {
            $data=input('post.');
            if(!empty($data["redirect"]) and substr($data["redirect"],0,4) != 'http'){
                $this->success('重定向网址不正确！');
            }
			$system_id=[];
            $arrid=Db::name('system')->where('type', 4)->column('id');
            if (isset($_FILES['img']["name"])) {
                foreach ($_FILES['img']["name"] as $k=>$v) {
                    if (!!$v) {
                        $system_id[]=$arrid[$k];
                    }
                }
            }
            $file = request()->file();
            if (isset($file['img'])) {
                    try {
                        validate(['img'=>'fileSize:5242880|fileExt:jpg,png,gif,webp,jpeg'])->check($file);
                        $file=$file['img'];
                        foreach ($system_id as $k=>$v) {
                            $info=\think\facade\Filesystem::disk('public')->putFile("slide", $file[$k]);
                            Db::name('system')->where('id', $v)->where('type', 4)->update(['value' => '/storage/'.strtr($info, " \ ", " / ")]);
                        }
                    } catch (\think\exception\ValidateException $e) {
                        $this->error($e->getMessage());
                    }

            }


            if ($data) {
                foreach ($data as $k => $v) {
                    $li=$system->where('enname', $k)->update(['value'  => trim($v)]);
                }
                return  $this->success('修改成功');
            }
            return $this->error('没有数据');
        }
        
        $data=$system->order('sort', 'ASC')->select();
        View::assign('data', $data);

        return View::fetch();
    }
    
    public function shield()
    {
        if (request()->isPost()) {
            $data=input('post.');
            $res=Db::name('shield')->where('id', 1)->update(['shield'=> $data['shield']]);
            if ($res!==false) {
                return  $this->success('修改成功');
            } else {
                return $this->error('修改失败！');
            }
            return;
        }
        
        $data=Db::name('shield')->where('id', 1)->find();
        View::assign('data', $data);

        return View::fetch();
    }
    public function config()
    {
        if (request()->isPost()) {
            $data=input('post.');
            foreach ($data as $k=>$v) {
                \app\manage\model\Config::update(['value' => $v], ['key' => $k]);
            }
            $this->success('修改成功');
        }
        $data=Db::name('config')->column('value', 'key');
        View::assign('data', $data);
        return View::fetch();
    }
    public function ya()
    {
        if (request()->isPost()) {
            set_time_limit(0);
            ini_set('memory_limit', '-1');
            ini_set('max_execution_time', '0');
            $data=input('post.');
            if(!\is_dir($data['type'])){
                $this->error('路径错误');
            }
            if(!$data["width"]){
                $this->error('宽度必须填写！');
            }
            $ar=$this->my_scandir($data['type']);
            foreach ($ar as $v){
                $img_info = getimagesize($v);
                if($img_info[0] > $data['width']){
                    $width=$data['width'];
                    if($data['height']){
                        $height=$data['height'];
                    }else{
                        $height=$img_info[1]*$width/$img_info[0];
                    }
                    $image = \think\Image::open($v);
                    $image->thumb($width, $height)->save($v);
                }
            }
            $this->success('压缩成功');
        }
        $arr=[];
        $arr[]=[
            'dir'=>root_path().'safe',
            'name'=>'safe',
        ];
        $dir=root_path().'public';
        $wo=scandir($dir);
        foreach($wo as $k=>$v){
            if(\is_dir($dir.'/'.$v)){
                if($v!='.' and $v!='..' and $v!='' and $v!='static'){
                    $arr[]=[
                        'dir'=>$dir.'/'.$v,
                        'name'=>$v,
                    ];
                }
            }
        }
        View::assign('arr', $arr);
        return View::fetch();
    }

    private function my_scandir($dir){
        static $files= array();
        if(is_dir($dir)){
            if($handle=opendir($dir)){
                while(($file=readdir($handle))!==false){
                    if($file!='.' && $file!=".."){
                        if(is_dir($dir."/".$file)){
                            $this->my_scandir($dir."/".$file);
                        }else{
                            $kzmar=explode(".",$file);//获取扩展名
                            if(isset($kzmar[1])){
                                $kzm=$kzmar[1];
                            }else{
                                $kzm='';
                            }
                            if($kzm=="gif" or $kzm=="jpg" or $kzm=="png" or $kzm=="GIF" or $kzm=="JPG" or $kzm=="PNG") { //文件过滤
                                $files[]=$dir."/".$file;  //获取文件的完全路径
                            }
                        }
                    }
                }
            }
        }
        closedir($handle);
        return $files;
    }

    public function tongji()
    {
        $config=config('app.tongji');
        $f='';
        $info='';
        if(!$config['ak'] or !$config['sk'] or !$config['maskId']){
           $f='51la参数错误，请设置参数后查看！';
        }else{
            list($s1, $s2) = explode(' ', microtime());
            $time= (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000);
            $noce=mt_rand(1000,9999);
            $data="accessKey={$config['ak']}&nonce=$noce&secretKey={$config['sk']}&timestamp=$time";
            $sign=hash("sha256", $data);
            $sign=strtoupper($sign);
            $url="https://v6-open.51.la/open/overview/get?maskId={$config['maskId']}&accessKey={$config['ak']}&nonce=$noce&timestamp=$time&sign=$sign";
            $info=$this->curl($url);
            if(!isset($info['success']) or !isset($info['code']) or !$info['success'] or $info['code']!= '0000'){
                $f='获取数据错误！';
            }
        }
        list($start, $end) = Time::today();
        $time=[
            [$start-6*24*60*60, $end-3*24*60*60],
            [$start-5*24*60*60, $end-4*24*60*60],
            [$start-4*24*60*60, $end-5*24*60*60],
            [$start-3*24*60*60, $end-6*24*60*60],
            [$start-2*24*60*60, $end-2*24*60*60],
            [$start-1*24*60*60, $end-1*24*60*60],
            [$start, $end],
        ];
        $ip_arr=[];
        $uv_arr=[];
        $pv_arr=[];
        $date=[];
        foreach ($time as $v){
            $date[]=date('Y-m-d',$v[0]);
            $ip_arr[]=Db::name('statistics')->where('time','>=',$v[0])->where('time','<',$v[1])->value('ip') ?: 0;
            $uv_arr[]=Db::name('statistics')->where('time','>=',$v[0])->where('time','<',$v[1])->value('uv') ?: 0;
            $pv_arr[]=Db::name('statistics')->where('time','>=',$v[0])->where('time','<',$v[1])->value('pv') ?: 0;
        }
        return View::fetch('',[
            'data'=>$info,
            'f'=>$f,
            'ip_arr'=>$ip_arr,
            'uv_arr'=>$uv_arr,
            'pv_arr'=>$pv_arr,
            'date_arr'=>$date
        ]);
    }
}
